const modules = new Map()

export const existingScript = (src) => modules.has(src)

export function loadScript(src) {
    const exist = existingScript(src)
    if (exist) return modules.get(src)

    return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = src
        script.id = src
        document.body.appendChild(script)


        script.onload = function () {
            document.body.removeChild(script)
            this.onerror = this.onload = null

            const key = Object.keys(window).pop()
            const res = window[key]
            const module = res.default ? res.default : res

            modules.set(src, module)
            resolve(module)
        }
        script.onerror = function () {
            this.onerror = this.onload = null
            reject(new Error('Failed to load ' + src), script)
        }
    })
}